import { useMemo } from "react";
import { useLocation } from "react-router-dom";
import { useMenu } from "@/hooks/useMenu";

export const OPERATIONS: { [key: string]: string } = {
  1: "add", // 添加
  2: "delete", // 删除
  3: "edit", // 编辑
  4: "view", // 查看
};

export interface OPremissionType {
  type: "add" | "delete" | "edit" | "view";
  children: React.ReactNode;
}

export const AddPremission = ({ children }: { children: React.ReactNode }) => (
  <OPremission type="add">{children}</OPremission>
);

export const DelPremission = ({ children }: { children: React.ReactNode }) => (
  <OPremission type="delete">{children}</OPremission>
);

export const EditPremission = ({ children }: { children: React.ReactNode }) => (
  <OPremission type="edit">{children}</OPremission>
);

export const ViewPremission = ({ children }: { children: React.ReactNode }) => (
  <OPremission type="view">{children}</OPremission>
);

export const OPremission = ({ type, children }: OPremissionType) => {
  const location = useLocation();
  const { premissionMaps } = useMenu();
  const isPremission = useMemo(() => {
    const { pathname } = location || "/";
    const operations = premissionMaps[pathname] || [];
    const operationTypes = [];
    for (const key in OPERATIONS) {
      if (Object.prototype.hasOwnProperty.call(OPERATIONS, key)) {
        const item = OPERATIONS[key];
        if (operations.includes(Number(key))) {
          operationTypes.push(item);
        }
      }
    }
    return operationTypes.includes(type);
  }, [location]);
  return <>{isPremission ? children : null}</>;
};

export default OPremission;
